package com.tau.egonetwork.gui.facebook;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;

import com.tau.egonetwork.common.Log;
import com.tau.egonetwork.gui.core.EgoNetworkMessageBox;
import com.tau.egonetwork.gui.interfaces.IPopupAnswerToTab;
import com.tau.egonetwork.gui.interfaces.IPopupResponse;
import com.tau.egonetwork.gui.interfaces.IRequestGUI;
import com.tau.egonetwork.threads.FacebookThread;

public class FacebookPopupResponse implements IPopupResponse {

	private final static String FAILURE_URL = "https://www.facebook.com/login/help.php";
	private final static String DENIED_URL = "http://engineering.tau.ac.il/?error=access_denied";
	private final static String SUCCESS_URL = "http://engineering.tau.ac.il/";
	
	private Shell _parent;
	private Shell _popupShell;
	private IPopupAnswerToTab _popupAnswerToTab;
	private IRequestGUI _facebookRequestGUI;
		
	public FacebookPopupResponse(Shell parent, IPopupAnswerToTab answer, IRequestGUI fbGUIRequest) {
		_parent = parent;
		_popupAnswerToTab = answer;
		_facebookRequestGUI = fbGUIRequest;
	}
	
	@Override
	public boolean onPopupResponse(String response) {
				
		Log.writeLineToLog("FacebookPopupResponse: " + response);
		
		if (response.startsWith(FAILURE_URL, 0)) {
			
			//user failed to enter correct login data several times:
			
			//first hide the popup:
			_popupShell.setVisible(false);
			
			//tell the user and ask him what to do:
			EgoNetworkMessageBox dialog = new EgoNetworkMessageBox(_parent, SWT.ICON_QUESTION, SWT.RETRY | SWT.CANCEL);
        	dialog.setText("Facebook Access");
        	dialog.setMessage("You have made several repeated failed attempts to access Facebook. Would you like to try again?");
        	int code = dialog.open();
        	
        	if (code == SWT.RETRY) {
        		if (_popupAnswerToTab != null)
            		_popupAnswerToTab.popupClosedWithCode(SWT.RETRY);
        	}
        	//else: user selected cancel (or exited using "X") --> close popup, do nothing        	
        	
        	//close popup no matter what (new one might be issued if Retry):
    		return true;
        	
		} else if (response.startsWith(DENIED_URL, 0)) {
			//user denied to give us access - close the popup
			return true;
		} else if (response.startsWith(SUCCESS_URL, 0)){
			
			//success! -> user entered correct data and has approved us :)
			
			//first of all hide pop-up:
			_popupShell.setVisible(false);
			
			//extract code from response:
			String pattern = "?code=";
			String code = response.substring(response.indexOf(pattern) + pattern.length());
			
			FacebookThread.invoke(_parent, code, _facebookRequestGUI);
			
			//close popup:
			return true;
		}
		
		//for any other case, we might be facing a redirection, or
		//a failed attempt with another shot or anything else
		//-- do not close the popup!:
		return false;
	}

	@Override
	public void registerPopup(Shell popupShell) {
		_popupShell = popupShell;
	}

}
